<template>
  <div class="order-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">
          <i class="icon-arrow-left"></i>
        </button>
        <h1 class="page-title">订单详情</h1>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>

    <!-- 订单详情 -->
    <div v-else-if="order" class="order-detail">
      <!-- 订单状态 -->
      <div class="status-section">
        <div class="status-icon">📦</div>
        <div class="status-info">
          <div class="status-text">{{ getStatusText(order.status) }}</div>
          <div class="status-desc">{{ getStatusDescription(order.status) }}</div>
        </div>
      </div>

      <!-- 收货信息 -->
      <div class="info-section">
        <h3 class="section-title">收货信息</h3>
        <div class="info-content">
          <div class="info-item">
            <span class="label">收货人：</span>
            <span class="value">{{ order.receiverName }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ order.receiverPhone }}</span>
          </div>
          <div class="info-item">
            <span class="label">收货地址：</span>
            <span class="value">{{ order.receiverAddress }}</span>
          </div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="info-section">
        <h3 class="section-title">订单信息</h3>
        <div class="info-content">
          <div class="info-item">
            <span class="label">订单号：</span>
            <span class="value">{{ order.orderNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">下单时间：</span>
            <span class="value">{{ formatTime(order.createdAt) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ getPaymentMethodText(order.paymentMethod) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付状态：</span>
            <span class="value">{{ getPaymentStatusText(order.paymentStatus) }}</span>
          </div>
          <div class="info-item" v-if="order.remark">
            <span class="label">订单备注：</span>
            <span class="value">{{ order.remark }}</span>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="products-section">
        <h3 class="section-title">商品信息</h3>
        <div class="products-list">
          <div 
            class="product-item" 
            v-for="item in order.orderItems" 
            :key="item.id"
          >
            <img 
              v-if="item.productImage" 
              :src="item.productImage" 
              :alt="item.productName"
              class="product-image"
            />
            <div v-else class="product-image-placeholder">
              {{ item.productName }}
            </div>
            <div class="product-info">
              <div class="product-name">{{ item.productName }}</div>
              <div class="product-price">¥{{ item.price }}</div>
              <div class="product-quantity">数量：{{ item.quantity }}</div>
            </div>
            <div class="product-subtotal">
              ¥{{ item.subtotal }}
            </div>
          </div>
        </div>
      </div>

      <!-- 订单总计 -->
      <div class="total-section">
        <div class="total-item">
          <span class="label">商品总价：</span>
          <span class="value">¥{{ order.totalAmount }}</span>
        </div>
        <div class="total-item">
          <span class="label">运费：</span>
          <span class="value">¥0.00</span>
        </div>
        <div class="total-item total">
          <span class="label">实付金额：</span>
          <span class="value">¥{{ order.totalAmount }}</span>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="actions-section">
        <button 
          v-if="order.status === 'PENDING'" 
          class="cancel-btn"
          @click="cancelOrder"
        >
          取消订单
        </button>
        <button 
          v-if="order.status === 'PENDING'" 
          class="pay-btn"
          @click="payOrder"
        >
          立即付款
        </button>
        <button 
          v-if="order.status === 'DELIVERED'" 
          class="confirm-btn"
          @click="confirmOrder"
        >
          确认收货
        </button>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-state">
      <div class="error-icon">❌</div>
      <p class="error-text">订单不存在或已被删除</p>
      <button class="back-home-btn" @click="goHome">返回首页</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useOrderStore } from '@/stores/order'
import { useUserStore } from '@/stores/user'
import type { Order } from '@/api/order'

// 路由
const router = useRouter()
const route = useRoute()

// 状态管理
const orderStore = useOrderStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)

// 计算属性
const order = computed(() => orderStore.currentOrder)

// 生命周期
onMounted(() => {
  loadOrderDetail()
})

// 方法
const loadOrderDetail = async () => {
  const userId = userStore.user?.id
  const orderId = route.params.id
  
  if (userId && orderId) {
    loading.value = true
    try {
      await orderStore.fetchOrderDetail(userId, Number(orderId))
    } catch (error) {
      console.error('加载订单详情失败:', error)
    } finally {
      loading.value = false
    }
  }
}

const goBack = () => {
  router.back()
}

const goHome = () => {
  router.push('/')
}

const cancelOrder = async () => {
  if (!confirm('确定要取消这个订单吗？')) {
    return
  }
  
  const userId = userStore.user?.id
  const orderId = route.params.id
  
  if (!userId || !orderId) return
  
  const result = await orderStore.cancelOrderById(userId, Number(orderId))
  if (result.success) {
    alert('订单取消成功')
    await loadOrderDetail()
  } else {
    alert('取消订单失败: ' + result.message)
  }
}

const payOrder = () => {
  // 这里实现支付逻辑
  alert('跳转到支付页面')
}

const confirmOrder = () => {
  // 这里实现确认收货逻辑
  alert('确认收货功能待实现')
}

const getStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'PENDING': '待付款',
    'PAID': '已付款',
    'SHIPPED': '已发货',
    'DELIVERED': '已送达',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || '未知状态'
}

const getStatusDescription = (status: string) => {
  const descMap: { [key: string]: string } = {
    'PENDING': '请尽快完成付款',
    'PAID': '商家正在处理您的订单',
    'SHIPPED': '商品正在配送中',
    'DELIVERED': '商品已送达，请及时签收',
    'COMPLETED': '订单已完成',
    'CANCELLED': '订单已取消'
  }
  return descMap[status] || ''
}

const getPaymentMethodText = (method: string) => {
  const methodMap: { [key: string]: string } = {
    'ALIPAY': '支付宝',
    'WECHAT': '微信支付',
    'BANK_CARD': '银行卡',
    'CASH': '现金'
  }
  return methodMap[method] || '未知方式'
}

const getPaymentStatusText = (status: string) => {
  const statusMap: { [key: string]: string } = {
    'UNPAID': '未支付',
    'PAID': '已支付',
    'REFUNDED': '已退款'
  }
  return statusMap[status] || '未知状态'
}

const formatTime = (time: string) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
.order-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #333;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.order-detail {
  padding: 16px;
}

.status-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-icon {
  font-size: 32px;
}

.status-info {
  flex: 1;
}

.status-text {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.status-desc {
  font-size: 14px;
  color: #666;
}

.info-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
}

.info-item .label {
  width: 80px;
  color: #666;
  font-size: 14px;
}

.info-item .value {
  flex: 1;
  color: #333;
  font-size: 14px;
}

.products-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.product-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
}

.product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.product-image-placeholder {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  text-align: center;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.product-price {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.product-quantity {
  font-size: 12px;
  color: #999;
}

.product-subtotal {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.total-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
}

.total-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.total-item:last-child {
  margin-bottom: 0;
  padding-top: 12px;
  border-top: 1px solid #eee;
}

.total-item.total {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.total-item .label {
  color: #666;
}

.total-item .value {
  color: #333;
}

.actions-section {
  padding: 16px;
  display: flex;
  gap: 12px;
}

.cancel-btn,
.pay-btn,
.confirm-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f8f9fa;
  color: #666;
  border: 1px solid #dee2e6;
}

.pay-btn {
  background-color: #007bff;
  color: white;
}

.confirm-btn {
  background-color: #28a745;
  color: white;
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.error-icon {
  font-size: 48px;
  color: #dc3545;
  margin-bottom: 16px;
}

.error-text {
  color: #666;
  margin-bottom: 20px;
}

.back-home-btn {
  padding: 12px 24px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}
</style> 